<template>
  <AffectedRowsCell v-if="view === 'AFFECTED_ROWS'" v-bind="props" />
  <ErrorCell v-if="view === 'ERROR'" v-bind="props" />
  <StatusUpdateCell v-if="view === 'STATUS_UPDATE'" v-bind="props" />
  <TransactionControlCell
    v-if="view === 'TRANSACTION_CONTROL'"
    v-bind="props"
  />
  <DatabaseSyncCell v-if="view === 'DATABASE_SYNC'" v-bind="props" />
  <div v-if="view === 'N/A'" class="text-control-placeholder">-</div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { TaskRunLogEntry_Type } from "@/types/proto/v1/rollout_service";
import type { Sheet } from "@/types/proto/v1/sheet_service";
import type { FlattenLogEntry } from "../common";
import AffectedRowsCell from "./AffectedRowsCell.vue";
import DatabaseSyncCell from "./DatabaseSyncCell.vue";
import ErrorCell from "./ErrorCell.vue";
import StatusUpdateCell from "./StatusUpdateCell.vue";
import TransactionControlCell from "./TransactionControlCell.vue";

type View =
  | "N/A"
  | "ERROR"
  | "AFFECTED_ROWS"
  | "STATUS_UPDATE"
  | "TRANSACTION_CONTROL"
  | "DATABASE_SYNC";

const props = defineProps<{
  entry: FlattenLogEntry;
  sheet?: Sheet;
}>();

const view = computed((): View => {
  const {
    type,
    commandExecute,
    taskRunStatusUpdate,
    transactionControl,
    databaseSync,
  } = props.entry;
  if (type === TaskRunLogEntry_Type.COMMAND_EXECUTE && commandExecute) {
    if (!commandExecute.raw.response) {
      return "N/A";
    }
    if (commandExecute.raw.response.error) {
      return "ERROR";
    }
    if (typeof commandExecute.affectedRows !== "undefined") {
      return "AFFECTED_ROWS";
    }
    if (typeof commandExecute.raw.response.affectedRows !== "undefined") {
      return "AFFECTED_ROWS";
    }
  }
  if (
    type === TaskRunLogEntry_Type.TASK_RUN_STATUS_UPDATE &&
    taskRunStatusUpdate
  ) {
    return "STATUS_UPDATE";
  }
  if (type === TaskRunLogEntry_Type.TRANSACTION_CONTROL && transactionControl) {
    return "TRANSACTION_CONTROL";
  }
  if (type === TaskRunLogEntry_Type.DATABASE_SYNC && databaseSync) {
    return "DATABASE_SYNC";
  }
  return "N/A";
});
</script>
